import { Injectable, ɵConsole } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Tool } from '@/app/common/utils/tool/tool';
import { GlobalService } from '@/app/common/global/global.service';
import { NzMessageService } from 'ng-zorro-antd/message';

@Injectable({
    providedIn: 'root',
})
export class AuthGuard implements CanActivate {

    //白名单数组
    private urlList: string[] = [
        '/login',
        '/auth/login'
    ];

    private permission_pages = null;

    constructor(
        private router: Router,
        private globalService: GlobalService,
        private tool: Tool,
        private message: NzMessageService
    ) {

    }

    /**当前路由 */
    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): boolean {
        let url: string = state.url;
        if (this.hasUrl(this.urlList, url)) {
            return true;
        } else {
            if (!this.permission_pages) {
                let global = this.globalService.get();
                if (global && global.pages) {
                    this.permission_pages = global.pages;
                }
            }
            return this.checkLogin(url, route);
        }
    }

    /**判断是否登录 */
    checkLogin(url: string, route: any): boolean {
        let token = this.tool.getToken(), flag = false;
        if (token != null && token != '') {
            if (route.data && route.data.permission) {
                for (let i = 0, leng = route.data.permission.length; i < leng; i++) {
                    let permission = '/' + route.data.permission[i];
                    if (this.permission_pages[permission]) {
                        flag = true;
                        break;
                    }
                }
            } else {
                flag = true;
            }
            if (!flag) {
                this.message.create('error', '你没有权限访问此菜单！');
            }
        }
        if (flag) {
            return true;
        }
        // 未登录,跳转到登录页面
        this.router.navigate(['/login']);
    }

    /**判断路径是否属于白名单 */
    hasUrl(urlList: string[], url: string): boolean {
        let flag: boolean = false;
        let _url = url.indexOf('?') >= 0 ? url.substr(0, url.indexOf('?')) : url;
        if (urlList.indexOf(_url) >= 0) {
            flag = true;
        }
        return flag;
    }


}